package com.algorithm.code.hash;

/**
 * @description 仅使用链表完成ＬＲＵ算法
 * @program: sudy
 * @author: kukuxiahuni
 * @create: 2020-01-23 19:44
 **/
public class LRUOnlyList<K, V> implements LRUAlgorithm<K, V> {

    /**
     * @Description: 链表节点
     * @Param key:节点的键
     * @return:
     * @Author: kukuxiahuni
     * @Date: 2020/1/23
     */
    private final static class Node<K, V> {
        K key;
        V value;
        /**
         * 节点下一个指针
         */
        Node<K, V> next;
    }

    /**
     * 缓存最大容量
     */
    private final int capacity = 5;

    /**
     * 固定头结点
     */
    private final Node<K, V> head = new Node<>();

    /**
     * 尾节点
     */
    private Node<K, V> tail = head;

    /**
     * 当前缓存的数据量
     */
    private int size = 0;

    /**
     * @Description: 1. 头指针删除
     * ２．　尾指针用于删除
     * @Param:
     * @return:
     * @Author: kukuxiahuni
     * @Date: 2020/1/23
     */
    @Override
    public void add(K key, V value) {
        if (key == null) {
            return;
        }

        /**
         * 找到ｋｅｙ的位置
         */
        Node<K, V> p = this.head;
        Node<K, V> tmp = null;
        while (p.next != null) {
            if (p.next.key.equals(key)) {
                p.next.value = value;
                tmp = p.next;
            }
            p = p.next;
        }

        //直接移动元素到末尾就好了
        if (tmp != null) {
            p.next = tmp.next;
            tail.next = tmp;
            tail = tmp;
            return;
        }

        /**
         * 1, 没找到，判断缓存是不是满了
         * 2. 满了： 删除头结点
         */
        if (size >= capacity) {
            head.next = head.next.next;
        }

        Node<K, V> node = new Node<>();
        node.key = key;
        node.value = value;
        node.next = null;
        tail.next = node;
        tail = node;
    }

    @Override
    public void delete(K key) {

    }

    @Override
    public V get(K key) {
        return null;
    }
}
